
#include "debris.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/gl.h>


void debrisDisable(Debris *toBeRemoved, Debris *prev)
{
	if(prev==NULL) // head to be removed
		debris_enabled_head = toBeRemoved->next;
	else
	  prev->next = toBeRemoved->next;
	  
	toBeRemoved->next = debris_disabled_head;
	debris_disabled_head = toBeRemoved;
}


Debris *moreDebris(int listSize)
{
	Debris *head = NULL;
	int loop;
	Debris *debris;

    for(loop=0; loop<listSize; loop++)
    {

		if ((debris = malloc(sizeof(*debris))) == NULL) {
      		printf("failed to alloc memory for debris\n");
      		(void)exit(EXIT_FAILURE);
    	}
    	debris->x = 0.0f;
    	debris->y = 0.0f;
    	debris->angle = 0.0f;
		debris->cr = 1.0f;
		debris->cg = 1.0f;
		debris->cb = 1.0f;
		debris->debrisType = 0;
		debris->direction = 270.0f;
		debris->rotation = 1;
		debris->speed = 0.1;
		debris->ageCounter = 100;

    	debris->next = head;
    	head = debris;
    }
    printf("allocated %d more debris\n", listSize);
    return(head);
}

Debris *debrisGetNew() 
{
	if(debris_disabled_head==NULL)
	{
		debris_disabled_head = moreDebris(50);
	}
	Debris *tmp = debris_enabled_head;
	debris_enabled_head = debris_disabled_head;
	debris_disabled_head = debris_disabled_head->next;
	debris_enabled_head->next = tmp;
	return debris_enabled_head;
}


void debrisInit(int listSize)
{
	debris_enabled_head = NULL;
	debris_disabled_head = moreDebris(listSize);
}

void debrisDrawUpdate()
{
	Debris *debris;
	Debris *prev = NULL;
	debris = debris_enabled_head;
  
	while(debris!=NULL)
	{

		
		glColor3f(debris->cr,debris->cg,debris->cb);
		
		glLoadIdentity();
		debris->x+=cos(debris->direction/180 * 3.1459f)*debris->speed;
		debris->y+=sin(debris->direction/180 * 3.1459f)*debris->speed;
		glTranslatef(debris->x,debris->y,0.0f);
		glRotatef(debris->angle, 0.0f, 0.0f, 1.0f);
		debris->angle += debris->rotation;
		
		glBegin(GL_LINES);
		glVertex2d(0,0);
		glVertex2d(0, debris->length);
		glEnd();
	
		
	  	if(debris->x < 0 || debris->x > 680 || debris->y < 0 || debris->y > 480 || debris->ageCounter--<0)
	  	{
	  		debrisDisable(debris, prev);
	  		if(prev!=NULL)
	  			debris = prev->next;
	  		else
	  			debris = debris_enabled_head;
	  	}
	  	else
	  	{
	  		prev = debris;
	  		debris = debris->next;
	    }	
	}
}	

